<template>
    <div>
        <div style="width:100%;margin-left:0px;">
            <div :id="chartId" :style="{ height: chartHeight + 'px' }" />
            <i class="iconfont icon-hengxiangzhuzhuangtu" v-if="isSort" style="font-size: 14px; margin-right: 5px; cursor: pointer;top: 15px; right: 10px; position: absolute; color: white;" @click="setSort()" />
            <i class="iconfont icon-hengxiangzhuzhuangtu1" v-if="!isSort" style="font-size: 14px; margin-right: 5px; cursor: pointer; top: 15px; right: 10px; position: absolute; color: white;" @click="setSort()" />
        </div>
    </div>
</template>

<script>
    export default {
        props: {
            titleText: { required: true, type: String },
            chartId: { required: true, type: String },
            chartHeight: { required: true, type: Number },
            dataLevel: { required: false, type: Object, default: () => { } },
            chartData: { required: false, type: Array, default: () => [] },
            chartBgColor: { required: false, type: String, default: "transparent" },
            tooltipBackgroundColor: { required: false, type: String, default: ["rgba(44, 135, 213, 0.3)"] }, 
            chartXData: {
                required: false,
                type: Array,
                default: () => ["等级修理", "巡检巡修", "保障科研", "器材筹供"],
            },
            xaxisData: {
                required: false,
                type: Array,
                default: () => [
                    "1月",
                    "2月",
                    "3月",
                    "4月",
                    "5月",
                    "6月",
                    "7月",
                    "8月",
                    "9月",
                    "10月",
                    "11月",
                    "12月",
                ],
            },
            yaxisName: { required: false, type: String, default: "个" },
            yaxisData1: {
                required: false,
                type: Array,
                default: () => [20, 50, 44, 30, 14, 88, 44, 50, 40, 50, 40],
            },
            yaxisData2: {
                required: false,
                type: Array,
                default: () => [65, 30, 44, 50, 65, 19, 50, 60, 15, 70, 55],
            },
            yaxisData3: {
                required: false,
                type: Array,
                default: () => [70, 60, 78, 40, 25, 49, 40, 15, 50, 70, 25],
            },
            yaxisData4: {
                required: false,
                type: Array,
                default: () => [20, 30, 18, 70, 25, 59, 40, 65, 50, 70, 25],
            },
            chartColor: {
                required: false,
                type: Array,
                default: () => ["#5470c6", "#91cc75", "#fac858", "#ee6666"],
            },
            txtColor:{
            required: false,
                type: Array,
                default: () => ["#000000"],
                },
            },
        data() {
            return {
                myChart: null,
                isSort:true,
            };
        },
        watch: {
            dataLevel(data) {
                if (data) {
                    //this.initChart();
                }
            }
        },
        mounted() { },
        methods: {
            initChart() {
                var _this = this;
                if (this.myChart) {
                    document
                        .getElementById(this.chartId)
                        .removeAttribute("_echarts_instance_");
                };
                const dataArray = []
                const datald = []
                const allData = [];
                this.dataLevel.data[0].data.forEach(x => {
                    allData.push(0);
                });
                this.dataLevel.data.map(item => {
                    datald.push(item.name)
                    const dataObj = {
                        name: item.name,
                        type: 'bar',
                        barWidth: '12',
                        stack: '总量',
                        itemStyle: {
                            color: item.type == 1 ? '#00994C' :
                                item.type == 2 ? '#0083D3' :
                                    item.type == 3 ? '#FF7F00' : '#FFB600'
                        },
                        label: {
                            normal: {
                                show: false,
                                position: 'insideRight'
                            }
                        },
                        data: item.data
                    }
                    dataArray.push(dataObj)
                });
                this.dataLevel.data.forEach((x, i) => {
                    x.data.forEach((y, l) => {
                        allData[l] = y + allData[l]
                    })
                });
                var arr1 = [];
                var arr2 = [];//y轴
                var arr3 = [];//总数
                var arr4 = [];//y对应x轴长度
                this.dataLevel.dataY.forEach((a, b) => {
                    arr1.push({ name: a, value: allData[b], obj: [] })
                });
                if (this.isSort) { //不排序
                    arr2 = arr1.map(x => x.name);
                    arr3 = arr1.map(x => x.value);
                    arr4 = JSON.parse(JSON.stringify(dataArray));
                    arr4.map(x => {
                        x.data.reverse();
                        return x
                    });
                    
                    arr2.reverse();
                    arr3.reverse();
                    arr4.push(
                        {
                            name: '总计',
                            type: 'bar',
                            barWidth: '12',
                            barGap: '-90%',
                            data: arr3,
                            label: {
                                normal: {
                                    color: '#fff',
                                    show: true,
                                    position: 'right'
                                }
                            },
                            itemStyle: {
                                color: 'rgba(0,0,0,0)'
                            }
                        }
                    )
                } else {
                    dataArray.forEach(y => {
                        arr1.forEach((x, i) => {
                            x.obj.push(y.data[i])
                        })
                    });
                    arr1.sort(function (a, b) {
                        return a.value - b.value;
                    });
                    arr2 = arr1.map(x => x.name);
                    arr3 = arr1.map(x => x.value);
                    arr4 = JSON.parse(JSON.stringify(dataArray));
                    arr4.map(x => {
                        x.data.reverse();
                        return x
                    });
                    arr4.forEach((a, b) => {
                        arr1.forEach((x,c) => {
                            a.data[c] = x.obj[b]
                        })
                    });
                    arr4.push(
                        {
                            name: '总计',
                            type: 'bar',
                            barWidth: '12',
                            barGap: '-90%',
                            data: arr3,
                            label: {
                                normal: {
                                    color: '#fff',
                                    show: true,
                                    position: 'right'
                                }
                            },
                            itemStyle: {
                                color: 'rgba(0,0,0,0)'
                            }
                        }
                    )
                };

                //for (var n = 0; n < month.length; n++) {

                //    var res = [];
                //    //alert(jdData.length);
                //    for (let j = 0; j < data[n].length; j++) {
                //        res.push({
                //            name: jdData[n][j],
                //            value: data[n][j]
                //        });

                //    }

                //    res.sort(function (a, b) {
                //        return b.value - a.value;
                //    }).slice(0, 6);

                //    res.sort(function (a, b) {
                //        return a.value - b.value;
                //    });


                //    var res1 = [];
                //    var res2 = [];
                //    //console.log(res);
                //    for (let t = 0; t < res.length; t++) {
                //        res1[t] = res[t].name;
                //        res2[t] = res[t].value;
                //    };

                //    option.options.push({
                //        title: {
                //            text: month[n] + '月'
                //        },
                //        yAxis: {
                //            data: res1,
                //        },
                //        series: [{
                //            data: res2
                //        }, {
                //            data: res2
                //        }]
                //    });
                //};
                const option = {
                    backgroundColor: 'transparent',
                    tooltip: { //鼠标悬浮窗
                        backgroundColor: this.tooltipBackgroundColor[0],
                        textStyle: {
                            color: 'white',
                            fontSize: 14
                        },
                        trigger: 'axis',
                        axisPointer: { // 坐标轴指示器，坐标轴触发有效
                            type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
                        },
                        formatter: function (val) {
                            let name = ''
                            let seriesName = ''
                            val.map(item => {
                                name = item.name
                                seriesName += item.seriesName + '：' + item.value + '条</br>'
                            })
                            return name + '</br>' + seriesName
                        }
                    },
                    legend: { // 顶上分类块
                        data: datald,
                        itemGap: 17,
                        textStyle: {
                            color: 'white',
                            fontSize: 14
                        }
                    },
                    grid: {
                        top: '4%',
                        left: '3%',
                        right: '5%',
                        bottom: '2%',
                        containLabel: true
                    },
                    xAxis: {
                        type: 'value',
                        axisLine: {
                            show: true,
                            lineStyle: {
                                color: 'white'
                            }
                        },
                        splitLine: {
                            show: false
                        },
                        axisTick: {
                            show: true
                        }
                    },
                    yAxis: {
                        type: 'category',
                        data: arr2,
                        axisLine: {
                            show: true,
                            lineStyle: {
                                color: 'white'
                            }
                        },
                        splitLine: {
                            show: false
                        },
                        axisTick: {
                            show: false
                        }
                    },
                    series: arr4
                };
                
                // 基于准备好的dom，初始化echarts实例
                this.myChart = echarts.init(document.getElementById(this.chartId));
                let charts = echarts.getInstanceByDom(
                    document.getElementById(this.chartId)
                );
                charts.getZr().off("click"); // 先取消点击，再触发，免得造成连续抖动触发
                charts.getZr().on("click", function (params) {
                    let pointInPixel = [params.offsetX, params.offsetY];

                    if (charts.containPixel("grid", pointInPixel)) {
                        let pointInGrid = charts.convertFromPixel(
                            {
                                seriesIndex: 0,
                            },
                            pointInPixel
                        );
                        let xIndex = pointInGrid[1]; // 索引
                        let handleIndex = Number(xIndex);
                        //let seriesObj = charts.getOption(); // 图表object对象

                        let op = charts.getOption();
                        let valueX = op.yAxis[0].data[op.yAxis[0].axisPointer.value];//获取点击的坐标所在地,这里是纵向的,所以我们取得是yAxis
                        _this.$emit("selectX", valueX);
                    }
                });
                // 绘制图表
                this.myChart.setOption(
                    option
                );
            },
            setSort() {
                this.isSort = !this.isSort;
                this.initChart();
            },
           
        },
        template: "#template"
    };
</script>
<style scoped>
    .view_chart {
        width: 100%;
        padding: 20px 10px 0;
    }
</style>
